import 'package:leancloud_rest_api/leancloud_rest_api.dart';

class UserModal extends LraBaseModel {
  String? name;

  UserModal({this.name});

  UserModal.fromJson(Map<dynamic, dynamic> json) {
    super.fromJson(json);
    name = json['name'];
  }
}

class BookModal extends LraBaseModel {
  String? title;
  String? author;
  String? price;
  String? image;
  UserModal? owner;

  BookModal({this.title, this.author, this.price, this.image});

  BookModal.fromJson(Map<dynamic, dynamic> json) {
    super.fromJson(json);
    title = json['title'];
    author = json['author'];
    price = json['price'];
    image = json['image'];

    owner = LraBaseModel.decodeNestedObject(json, 'owner', UserModal.fromJson);
  }
}

Future<void> main() async {
  var dbConfig = LraDbConfig(appId: '', appKey: '', serverUrl: '');
  var bookApi = LraRestApi<BookModal>(
    dbConfig,
    'Book',
    BookModal.fromJson,
  );

  var obj = await bookApi.get('objectId');
  print('Get $obj');

  // 详见 https://docs.leancloud.cn/sdk/storage/guide/rest/#%E6%9F%A5%E8%AF%A2
  var query = LraQuery(where: {
    'title': 'title',
    'createdAt': {
      '\$gte': DateTime.parse('2015-06-29T00:00:00.000Z'),
      '\$gt': DateTime.parse('2015-06-29T00:00:00.000Z'),
      '\$lte': DateTime.parse('2015-06-30T00:00:00.000Z'),
      '\$lt': DateTime.parse('2015-06-30T00:00:00.000Z'),
    },
    'upvotes': {
      '\$in': [1, 2, 3],
      '\$nin': [1, 2, 3]
    },
    'upvots': {'\$exists': true},
    'user': {
      '__type': 'Pointer',
      'className': '_User',
      'objectId': '55a39634e4b0ed48f0c1845c'
    },
    'title2': {'\$regex': '^WTO.*', '\$options': 'i'},
    'arrayKey': {
      '\$all': [2, 3, 4]
    },
    'arrayKey2': {'\$size': 3},
    'post': {
      '__type': 'Pointer',
      'className': 'Post',
      'objectId': '558e20cbe4b060308e3eb36c'
    },
    'post2': {
      '\$inQuery': {
        'where': {
          'image': {'\$exists': true}
        },
        'className': 'Post'
      }
    },
    '\$or': [
      {
        'pubUserCertificate': {'\$gt': 2}
      },
      {
        'pubUserCertificate': {'\$lt': 3}
      }
    ],
  });
  var objs = await bookApi.find(query);
  print('find $objs');
}
